
import React, { Component, PropTypes } from 'react';
import {
	Alert, Dimensions, StyleSheet, Text, View, ScrollView, TouchableOpacity, Platform,
} from 'react-native';
import { MtContainer, MtChar, MtEdit, MtFixedButton, MtLabelBar, MtToast, MtPopupPicker,MtNavBar,
	MtSeparator, MtDateTimePicker, MtColor, MtActionButton, MtListView, MtEmptyView } from 'martian-ui';
const DeviceCell = require('../components/DeviceCell');
import {fetchDeviceList} from '../action/girlAction';
import { bindActionCreators } from 'redux';
import dismissKeyboard from 'react-native/Libraries/Utilities/dismissKeyboard';
const { MtM3, MtL3, MtW2 } = MtChar;
import TipBar from '../components/TipBar';
import values from 'lodash/values';
import keys from 'lodash/keys';
import {connect} from 'react-redux';
const EntityLabels = require('../constants/entities');
import assign from 'lodash/assign';
import ManageActionDevice from '../container/ManageActionDevice';
import ScenceName from '../container/ScenceName';
import {creatScence} from '../action/girlAction';
import { modelToKeyString } from '../utils/modelToKeyString';
import NavigationBar from '../components/common/NavigationBar'
import LabelBar from '../components/common/ArgraceUI/LabelBar'
function defParams(parmas,deviceId) {
	const b = keys(parmas);
	const arr = [];
	for (let i = 0; i < b.length; i++) {
		const k = b[i];
		let r = /^\D+(?=\d)/.exec(k) || b[i];
		r = r.toString().substring(0,1).toUpperCase()+r.toString().substring(1);
		const n = /\d+/.exec(k);
		const c = {
			[`${r}${!n ? '' : `_${n}`}`]: parmas[b[i]],
			DeviceId: deviceId,
		};
		arr.push(c);
	}

	return arr;

}
function _renderRow(deviceId) {
	const { navigator } = this.props;
	return (
		<DeviceCell
			navigator={navigator}
			deviceId={deviceId}
			rightShowType={1}
			setValue={(value)=>{
				this.setState({ [`${deviceId}value`]:value ? "1" : '0' })
			}}
			setParams={(params)=>{
				const  a = defParams(params,deviceId)
				this.setState({ [`${deviceId}params`]:a || {}})
			}}


		/>
	);
}

function uniq(array){
	var temp = []; //一个新的临时数组
	for(var i = 0; i < array.length; i++){
		if(temp.indexOf(array[i]) == -1){
			temp.push(array[i]);
		}
	}
	return temp;
}

function removeA(arr) {
	var what, a = arguments, L = a.length, ax;
	while (L > 1 && arr.length) {
		what = a[--L];
		while ((ax= arr.indexOf(what)) !== -1) {
			arr.splice(ax, 1);
		}
	}
	return arr;
}


class AddSence extends Component {
	constructor(props) {
		super(props)
		// 初始状态
		this.state = {
			boolLink:['是','否'],
			delayTime: ['10秒','30秒','1分钟'],
		}
	}

	convertPropsToStates(props) {
		const { devicesEntities} = props;

		let newDeviceIds =[];
		if (devicesEntities && keys(devicesEntities).length > 0) {
			newDeviceIds = values(devicesEntities).map(ele => ele.deviceId);
		}

		const newState = assign({

			newDeviceIds,

		});

		if (newState) {
			this.setState(newState);
		}
	}

	componentWillReceiveProps(nextProps) {
		this.convertPropsToStates((nextProps));
	}
	componentWillMount() {
		this.convertPropsToStates(this.props);
	}

	render() {
		const  { newDeviceIds, addedDeviceIds} = this.state;
		const  { navigator,  devicesEntities, accessToken} = this.props;

		const that = this;
		const temp = addedDeviceIds ? uniq(addedDeviceIds && values(addedDeviceIds)):[]
		console.warn('temp'+JSON.stringify(temp))
		//房间场景
		const renderRowBind = _renderRow.bind(this);
		let V1;
		if (temp && temp.length > 0) {
			V1 = (
				<MtListView
					data={temp}
					renderRow={renderRowBind}
					initialListSize={10}
					scrollRenderAheadDistance={500}
					onEndReachedThreshold={10}
					renderSeparator={undefined}
					enableEmptySections={true}
					removeClippedSubviews={false}
					onRefresh={() => {
						//  this.refresh();
					}}
					onEndReached={() => {

					}}
				/>
			);
		}
		else {
			V1 = (
				<MtEmptyView
					onRefresh={() => {
					}}
					desc="您没有设备"

				/>
			);
		}
		return (
			<MtContainer>
				<ScrollView
					ref={(temp) => {
						this.scroll = temp;
					}}
					keyboardDismissMode="interactive"
					keyboardShouldPersistTaps="handled"
				>
          <NavigationBar
            title={'新增场景'}
            statusBar={{backgroundColor: '#ffffff', barStyle: 'dark-content'}}
            navigator={this.props.navigator}
            style={{borderBottomWidth: 1, borderColor: '#EDEDED', backgroundColor: '#ffffff'}}
          />
          <MtSeparator color={'#F4F4F4'} height={10} style={{ borderBottomColor: '#EDEDED', borderBottomWidth: 1 }} />
					<LabelBar
						onPress={() => {
							navigator.push({
								component: ScenceName,
								params: {
									fun: (new1) => {
											that.setState(assign({}, this.state, {scenceName: new1}))
										},
									navigator:navigator

									},

								})
							}}
						title="场景名称"
						titleStyle={{ width: 120 }}
						value={this.state.scenceName || ''}
						style={styles.textRight}
					/>
					<LabelBar
						onPress={() => {

						}}
						title="选择场景图标"
						titleStyle={{ width: 180 }}
						style={styles.textRight}
					/>
          <MtSeparator color={'#F4F4F4'} height={10} style={{ borderBottomColor: '#EDEDED', borderBottomWidth: 1, borderTopColor: '#EDEDED', borderTopWidth: 1 }} />
					<LabelBar
						onPress={() => {
							dismissKeyboard();
							this.boolLinkPopupView.open();
						}}
						title={'是否联动'}
						titleStyle={{ width: 150 }}
						value={this.state.linkStatus || ''}
						style={styles.textRight}
					/>
					<LabelBar
						onPress={() => {

						}}
						title="触发条件"
						titleStyle={{ width: 180 }}
						style={styles.textRight}
					/>
					<LabelBar
						onPress={() => {
							dismissKeyboard();
							this.delayPopupView.open();
						}}
						title={'场景延时'}
						titleStyle={{ width: 150 }}
						value={this.state.delayStatus || ''}
						style={styles.textRight}
					/>
          <MtSeparator color={'#F4F4F4'} height={10} style={{ borderBottomColor: '#EDEDED', borderBottomWidth: 1, borderTopColor: '#EDEDED', borderTopWidth: 1 }} />
					<LabelBar
						onPress={() => {
							navigator.push({
								component: ManageActionDevice,
								oldDeviceIds: addedDeviceIds && values(addedDeviceIds),
								params: {
									addfun: (new1) => {
										let obj = {};
										if (new1.length > 0){
											new1.forEach((ele) => {
												obj[`${ele}`] = ele
											})

											that.setState(assign({}, this.state, {addedDeviceIds: obj }))

										}
									},
									navigator:navigator

								}

							})
						}}
						title="执行设备"
						value="管理设备"
						titleStyle={{ width: 180 }}
            style={styles.manageDeviceTitleStyle}
            iconColor={'#333333'}
					/>
					{V1}
					<MtPopupPicker
						ref={
							(unitsPopupView) => {
								this.boolLinkPopupView = unitsPopupView;
							}
						}
						title=""
						options={this.state.boolLink}
						selectedOption={this.state.linkStatus}
						transformOption={option => option.toString()}
						onSelect={(item, index) => {
							this.setState({ linkStatus: item || this.state.boolLink[0] });
						}}
						onComplete={() => {
							this.setState({ linkStatus: this.state.linkStatus || this.state.boolLink[0] });
						}}
					/>
					<MtPopupPicker
						ref={
							(unitsPopupView) => {
								this.delayPopupView = unitsPopupView;
							}
						}
						title=""
						options={this.state.delayTime}
						selectedOption={this.state.delayStatus}
						transformOption={option => option.toString()}
						onSelect={(item, index) => {
							this.setState({ delayStatus: item || this.state.delayTime[0] });
						}}
						onComplete={() => {
							this.setState({ delayStatus: this.state.delayStatus || this.state.delayTime[0] });
						}}
					/>
				</ScrollView>
				<View style={{ height: 58, alignItems:'center', flexDirection:'row' ,backgroundColor:'#fff'}}>
					<TouchableOpacity
						onPress={()=> {
							navigator.pop()
						}}
						style={{ flex: 1,backgroundColor: '#fff'}}

					>
					<MtL3 style={{  paddingLeft: 20}}>
						返回重新配置
					</MtL3>
					</TouchableOpacity>
					<TouchableOpacity
						onPress={()=> {
							let obj = {};
							let actions1 = [];

							temp && temp.forEach(ele => {
								if(this.state[`${ele}params`]){
									this.state[`${ele}params`].forEach(ele1 => {
										actions1.push(ele1)
									})


								}else {
									obj['DeviceId'] = ele.toString();
									obj['Value'] = this.state[`${ele}value`] || 0;
									obj['key'] = modelToKeyString(devicesEntities[ele].model);
									actions1.push(obj)
								}

							});
							console.warn('Actions'+JSON.stringify(actions1))
							const params = {
								gatewayId: this.props.gatewayId,
								action: {"Action": actions1},
								type: "1",//房间场景
								name: this.state.scenceName || '',
								scope: 1,
								roomId: this.props.roomId,
							}
							this.props.creatScence(params, accessToken);
							navigator.pop()


						}}

						disabled={!addedDeviceIds}
						style={{ width: 120}}

					>
					<View style={{  height: 58, backgroundColor:'#24A7AC', alignItems:'center', justifyContent: 'center',}}>
						<MtW2>
							完成
						</MtW2>
					</View>
					</TouchableOpacity>
				</View>
			</MtContainer>

		);}
};


function mappingStateToProps(state, ownProps) {

	const entities= state['entities'];
	const devicesEntities = entities[EntityLabels.devices];
	const assessTokenEntity = entities[EntityLabels.token];
	const assessToken = assessTokenEntity && values(assessTokenEntity)[0].assessToken;

	return {
		devicesEntities,
		assessToken
	}
}
function mapDispatchToProps(dispatch) {
	const actions = {
		creatScence
	};
	return bindActionCreators(actions, dispatch);
}

module.exports = connect(mappingStateToProps, mapDispatchToProps)(AddSence);

const styles = StyleSheet.create({
	textRight: {
		textAlign: 'right',
	},
	manageDeviceTitleStyle:{
		textAlign: 'right',
		fontWeight: 'bold',
		fontSize: 13,
		color: '#333333',
	},
	textRightColor: {
		textAlign: 'right',
		color: MtColor.main,
	},
	listViewStyle:{
		// 改变主轴的方向
		flexDirection:'row',
		// 多行显示
		flexWrap:'wrap',
		// 侧轴方向
		alignItems:'center', // 必须设置,否则换行不起作用
	}
});
